import { history } from 'umi';
import { message } from 'antd';
import { parse } from 'qs';
import { userLogin, getFakeCaptcha } from './service';

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}
export function setAuthority(authority) {
  const proAuthority = authority;
  sessionStorage.setItem('token', JSON.stringify(proAuthority)); // hard code
  // reload Authorized component

  try {
    if (window.reloadAuthorized) {
      window.reloadAuthorized();
    }
  } catch (error) {
    // do not need do anything
  }

  return authority;
}
const Model = {
  namespace: 'userAndlogin',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {

  try {

      const response = yield call(userLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully
      if (response.token != "") {
        message.success('Login successfully!');
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        //window.location.href = urlParams
        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        window.location.href = '/dashboard/overview';
        // history.replace(redirect || '/');
        // history.replace('/dashboard/overview')
      }

  } catch (error) {
    const response = error
    response["status"] = "error"
    response["type"] = "account"

    yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

  }


    },

  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.token);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
